package com.example.wangzh.mytest.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.example.wangzh.mytest.R;

/**
 * Created by zhwang16 on 2018/9/20.
 * 用于测试View的onMeasure方法
 */

public class MeasureTestView extends LinearLayout {
    Button btn_longer, btn_shorter;
    int extraLengthRatio = 0;
    final static int EXTRA_LENGTH = 50;

    public MeasureTestView(Context context) {
        super(context);
        init(context, null);
    }

    public MeasureTestView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MeasureTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.custom_measure_test, this);
        btn_longer = (Button) findViewById(R.id.btn_longer);
        btn_shorter = (Button) findViewById(R.id.btn_shorter);
        btn_longer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                extraLengthRatio++;
                refresh();
            }
        });
        btn_shorter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                extraLengthRatio--;
                if (extraLengthRatio < 0) {
                    extraLengthRatio = 0;
                }
                refresh();
            }
        });
    }

    private void refresh() {
        postInvalidate();
        //一定要调用这个，使父布局重新排布
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //为什么必须调用super.onMeasure才能正常显示？？？
        int measuredWidth = getDefaultSize(500, widthMeasureSpec);
        int measuredHeight = getDefaultSize(500, heightMeasureSpec) + EXTRA_LENGTH * extraLengthRatio;
        setMeasuredDimension(measuredWidth, measuredHeight);
        postInvalidate();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }
}
